package com.fengwk.support.api;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.fengwk.support.constant.SupportConstant;
import com.fengwk.support.exception.BaseException;
import com.fengwk.support.util.CollectionUtils;
import com.fengwk.support.util.DateUtils;
import com.fengwk.support.util.HttpClientUtils;
import com.fengwk.support.util.JsonUtils;
import com.fengwk.support.util.LoggerUtils;
import com.fengwk.support.util.MapUtils;
import com.fengwk.support.util.ResultUtils;
import com.fengwk.support.util.TypeUtils;
import com.fengwk.support.util.LoggerUtils.Logger;
import com.fengwk.support.util.ResultUtils.JsonMap;

public abstract class AbstractApi {
	
	private static final Logger LOG = LoggerUtils.getLogger(AbstractApi.class);
	
	private static final ThreadLocal<Map<String, String>> PARAM_MAP_THREAD_LOCAL = new ThreadLocal<Map<String, String>>();
	
	/**
	 * 发送post请求,获取JsonMap对象
	 * @param url
	 * @return
	 */
	protected static JsonMap post(String url) {
		setParamMap(SupportConstant.CONNECTION_SECRET_KEY_KEY, SupportConstant.CONNECTION_SECRET_KEY_VALUE, false);
		Map<String, String> paramMap = PARAM_MAP_THREAD_LOCAL.get();
		PARAM_MAP_THREAD_LOCAL.remove();
		JsonMap jsonMap = null;
		try {
			jsonMap = JsonUtils.fromJson(
					HttpClientUtils.post(url, paramMap, null).getStringContent(), 
					JsonMap.class);
		} catch (Exception e) {
		    LOG.error(e.getMessage());
		}
		return jsonMap;
	}
	
	/**
	 * 参数表处理
	 * @param map
	 * @param key
	 * @param value 字段值
	 * @param required 必要字段
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected static void setParamMap(String key, Object value, boolean required) throws BaseException {
		if(required && value == null) {
			throw new BaseException(ResultUtils.PARAMETER_ERROR_CODE, "请求参数为空");
		}
		String valueBuf = null;
		if(value != null) {
			if(TypeUtils.isType(value.getClass(), Date.class)) {
				valueBuf = DateUtils.format((Date) value);
			} else if (TypeUtils.isType(value.getClass(), Collection.class)) {
				valueBuf = CollectionUtils.join((Collection) value);
			} else {
				valueBuf = value.toString();
			}
			Map<String, String> paramMap = PARAM_MAP_THREAD_LOCAL.get();
			if(MapUtils.isBlank(paramMap)) {
				paramMap = new HashMap<String, String>();
				PARAM_MAP_THREAD_LOCAL.set(paramMap);
			}
			paramMap.put(key, valueBuf);
		}
	}

}
